<?php

class ItemsController extends AppController {

    var $name = 'Items';
    var $uses = array('Item', 'Article', 'Sale');

    function beforeFilter() {
        parent::beforeFilter();

        
        //si no es un usuario con nivel = 2 o 1 no lo dejo acceder a las siguientes funciones de este controlador
        if (in_array($this->action, array('index', 'add', 'delete', 'view')) and $this->Auth->user('id') and !(in_array($this->Auth->user('level'), array(1,2)))) {
            $this->redirect(array('user' => false, 'controller' => 'items', 'action' => 'inicio'));
        }
        if (in_array($this->action, array('edit')) and $this->Auth->user('id')) {
            $this->redirect(array('user' => false, 'controller' => 'articles', 'action' => 'inicio'));
        }
    }

    function index() {
        $this->Item->recursive = 0;
        $this->set('items', $this->paginate());
    }

    function view($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Item no válido', true));
            $this->redirect(array('controller' => 'sales', 'action' => 'view', $this->data['Item']['sale_id']));
        }
        $this->set('item', $this->Item->read(null, $id));
    }

    function add() {
        //empiezo una transaccion
        $this->Item->query('SET AUTOCOMMIT = 0;');
        $this->Item->query('START TRANSACTION;');
        $bandera = true; //la uso para ver si algo salio mal

        if (!empty($this->data)) {
            $datos = $this->data;
                        
            //controlo que la cantidad de articulos que va a vender este disponible en el stock, sino, no lo dejo
            $this->Article->recursive = -1;
            $aux_art = $this->Article->read(null, $datos['Item']['article_id']);
            if($datos['Item']['sale_amount'] > $aux_art['Article']['amount_available']){
                $this->Session->setFlash('No se registro la venta porque se intetaron vender '.$datos['Item']['sale_amount'].' articulos y solo se dispone de '.$aux_art['Article']['amount_available'].' articulos en stock.');
                $this->redirect($this->referer());
            }
            
//                    pr($datos);die;
            //Busco el articulo para traerme el precio
            $articulo = $this->Article->query("SELECT PRICE as precio FROM articles WHERE articles.id = " . $datos['Item']['article_id'] . ";");
//                    pr($datos);die;
            if ($datos['Item']['retouch'] == 0) {
                $datos['Item']['retouch'] = 'NO';
                $datos['Item']['subtotal'] = $datos['Item']['price'] * $datos['Item']['sale_amount'];
            } else {
                $datos['Item']['retouch'] = 'SI';
                $datos['Item']['subtotal'] = 0;
            }
            
            if ($datos['Item']['phase_change'] == 0) {
                $datos['Item']['phase_chage'] = 'NO';
            } else {
                $datos['Item']['phase_chage'] = 'SI';
            }
//                    pr($datos['Item']['temp_price']);die;
            $datos['Item']['temp_price'] = $datos['Item']['price'];
            $this->Item->create();
            if ($this->Item->save($datos)) {

                //Actualizo el Total de la venta luego de cargado el nuevo item
                $venta = $this->Sale->find('first', array('conditions' => array('sale.sale_date', 'Sale.id' => $datos['Item']['sale_id'])));
                $aux = $this->Item->query("SELECT SUM(subtotal) as suma FROM items WHERE items.sale_id = " . $datos['Item']['sale_id'] . ";");

                $venta['Sale']['total'] = $aux[0][0]['suma'];
                //Otra Manera de guardar campos!
                $this->Sale->id = $venta['Sale']['id'];
                if ($this->Sale->saveField('total', $venta['Sale']['total'])) {
                    $this->Sale->saveField('sale_date', $venta['Sale']['sale_date']);
                    //Aca actualizo el articulo perteneciente a la compra descontandole la cantidad comprada
//                                $purchase = $this->Purchase->query("SELECT purchases.article_id as articulo, purchases.purchase_amount as cantidad FROM purchases WHERE purchases.id = ".$id.";");

                    $article = $this->Article->query("SELECT * FROM articles WHERE articles.id = " . $datos['Item']['article_id'] . ";");
                    $article[0]['articles']['amount_available'] = $article[0]['articles']['amount_available'] - $datos['Item']['sale_amount'];

//                    pr($article[0]['articles']);die;
                    $sql  = "UPDATE articles SET amount_available = amount_available - " .$datos['Item']['sale_amount']. " WHERE id = " .$datos['Item']['article_id']. "";
                    if ($this->Article->query($sql)) {
                        $bandera = true;
                    } else {
                        $bandera = false;
                    }
                    //Fin actualizacion articulo
                } else {
                    $bandera = false;
                }
                //Fin actualizacion
//				$this->Session->setFlash(__('El item se ha guardado', true));
//				$this->redirect(array('controller'=>'sales','action' => 'view', $this->data['Item']['sale_id']));
            } else {
                $bandera = false;
            }
            if ($bandera) {
                $this->Item->query('COMMIT;');
                $this->Item->query('SET AUTOCOMMIT = 1;');
//                            $this->Session->setFlash(__('El item se ha guardado', true));
                $this->redirect(array('controller' => 'sales', 'action' => 'view', $this->data['Item']['sale_id']));
            } else {//si hubo algun error hago un ROLLBACK deshaciendo todas estas consultas
                $this->Item->query('ROLLBACK;');
                $this->Item->query('SET AUTOCOMMIT = 1;');
                $this->Session->setFlash(__('El item no pudo ser guardado. Por favor corrobore los datos.', true));
//                            die('lala');
//                            $this->redirect(array('controller'=>'sales', 'action'=>'view', $this->data['Item']['sale_id'], $this->data));
                $this->Session->write('datos_mal_item', $this->data['Item']);
                $this->redirect(array('controller' => 'sales', 'action' => 'view', $this->data['Item']['sale_id']));
            }
        }
//		$articles = $this->Item->Article->find('list');
        $articulos = $this->Article->find('all', array('fields' => array('Article.mark', 'Article.model', 'Article.id'), 'conditions' => array('Article.termination_date' => NULL)));
        $articles = array();
        foreach ($articulos as $art) {
            $articles[$art['Article']['id']] = $art['Article']['mark'] . ' - ' . $art['Article']['model'];
        }
//		$sales = $this->Item->Sale->find('list');
        $ventas = $this->Sale->find('all', array('fields' => array('Sale.sale_date', 'Sale.id')));
        $sales = array();
        foreach ($ventas as $vent) {
            $sales[$vent['Sale']['id']] = $vent['Sale']['sale_date'];
        }
        $this->set(compact('articles', 'sales'));
    }

    function edit($id = null) {
        //empiezo una transaccion
        $this->Item->query('SET AUTOCOMMIT = 0;');
        $this->Item->query('START TRANSACTION;');
        $bandera = true; //la uso para ver si algo salio mal

        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Item no válido', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            $datos = $this->data;
//                    pr($datos);die;
            $aux = $this->Item->query("SELECT SALE_AMOUNT as cantidad1 FROM items WHERE items.id =" . $datos['Item']['id'] . ";");
//                    pr($aux);
            $cantidad_original = $aux[0]['items']['cantidad1'];
//                    pr($cantidad_original);die;
            $articulo = $this->Article->find('first', array('conditions' => array('Article.id' => $datos['Item']['article_id'])));
            $datos['Item']['temp_price'] = $articulo['Article']['price'];
            $datos['Item']['subtotal'] = $datos['Item']['temp_price'] * $datos['Item']['sale_amount'];
            if ($datos['Item']['retouch'] == 0) {
                $datos['Item']['retouch'] = 'NO';
            } else {
                $datos['Item']['retouch'] = 'SI';
            }
//                    pr($datos);die;
            if ($this->Item->save($datos)) {

                //Actualizo el Total de la venta luego de cargado el nuevo item
                $venta = $this->Sale->find('first', array('conditions' => array('Sale.sale_date', 'Sale.id' => $datos['Item']['sale_id'])));
                $aux = $this->Item->query("SELECT SUM(subtotal) as suma FROM items WHERE items.sale_id = " . $datos['Item']['sale_id'] . ";");

                $venta['Sale']['total'] = $aux[0][0]['suma'];
                //Otra Manera de guardar campos!
                $this->Sale->id = $venta['Sale']['id'];
                if ($this->Sale->saveField('total', $venta['Sale']['total'])) {
                    $this->Sale->saveField('sale_date', $venta['Sale']['sale_date']);
                    //Aca actualizo el articulo perteneciente a la compra descontandole la cantidad comprada
//                                $purchase = $this->Purchase->query("SELECT purchases.article_id as articulo, purchases.purchase_amount as cantidad FROM purchases WHERE purchases.id = ".$id.";");

//                    $article = $this->Article->find('first', array('conditions' => array('Article.id' => $datos['Item']['article_id'])));
                    $articulo['Article']['amount_available'] = $articulo['Article']['amount_available'] - $datos['Item']['sale_amount'];
                    $articulo['Article']['amount_available'] = $articulo['Article']['amount_available'] + $cantidad_original;

                    if ($this->Article->save($articulo['Article'])) {
                        $bandera = true;
                    } else {
                        $bandera = false;
                    }
                    //Fin actualizacion articulo
                } else {
                    $bandera = false;
                }
                //Fin actualizacion
//				$this->redirect(array('controller'=>'sales','action' => 'view', $datos['Item']['sale_id']));
            } else {
//				$this->Session->setFlash(__('El item no pudo ser salvado. Por favor, inténtalo de nuevo.', true));
                $bandera = false;
            }
            if ($bandera) {
                $this->Item->query('COMMIT;');
                $this->Item->query('SET AUTOCOMMIT = 1;');
//                            $this->Session->setFlash(__('El item se ha guardado', true));
                $this->redirect(array('controller' => 'sales', 'action' => 'view', $this->data['Item']['sale_id']));
            } else {//si hubo algun error hago un ROLLBACK deshaciendo todas estas consultas
                $this->Item->query('ROLLBACK;');
                $this->Item->query('SET AUTOCOMMIT = 1;');
                $this->Session->setFlash(__('El item no pudo ser salvado. Por favor, inténtalo de nuevo.', true));
            }
        }

        if (empty($this->data)) {
            $this->data = $this->Item->read(null, $id);
//            pr($this->data);die;
            $fecha = date('d/m/Y', strtotime($this->data['Sale']['sale_date']));
            $this->set(compact('fecha'));
        }
//		$articles = $this->Item->Article->find('list');
        $articulos = $this->Article->find('all', array('fields' => array('Article.mark', 'Article.model', 'Article.id'), 'conditions' => array('Article.termination_date' => NULL)));
        $articles = array();
        foreach ($articulos as $art) {
            $articles[$art['Article']['id']] = $art['Article']['mark'] . ' - ' . $art['Article']['model'];
        }

        $ventas = $this->Sale->find('all', array('fields' => array('Sale.sale_date', 'Sale.id')));
        $sales = array();
        foreach ($ventas as $vent) {
            $sales[$vent['Sale']['id']] = $vent['Sale']['sale_date'];
        }
        $this->set(compact('articles', 'sales'));
    }

    function delete($id = null) {
        //empiezo una transaccion
        $this->Item->query('SET AUTOCOMMIT = 0;');
        $this->Item->query('START TRANSACTION;');
        $bandera = true; //la uso para ver si algo salio mal

        if (!$id) {
            $this->Session->setFlash(__('No válida de identificación para el item', true));
            $this->redirect(array('action' => 'index'));
        }
        $datos = $this->Item->find('first', array('conditions' => array('Item.id' => $id)));
//                pr($datos);die;
        if ($this->Item->delete($id)) {

            //Actualizo el Total de la venta luego de cargado el nuevo item
            $venta = $this->Sale->find('first', array('conditions' => array('Sale.sale_date', 'Sale.id' => $datos['Item']['sale_id'])));
            $aux = $this->Item->query("SELECT SUM(subtotal) as suma FROM items WHERE items.sale_id = " . $datos['Item']['sale_id'] . ";");

            $venta['Sale']['total'] = $aux[0][0]['suma'];
            //Otra Manera de guardar campos!
            $this->Sale->id = $venta['Sale']['id'];            
            if ($this->Sale->saveField('total', $venta['Sale']['total'])) {
                $this->Sale->saveField('sale_date', $venta['Sale']['sale_date']);
                //Actualizo el Total de la venta luego de cargado el nuevo item
                $venta = $this->Sale->find('first', array('conditions' => array('Sale.id' => $datos['Item']['sale_id'])));
                $aux = $this->Item->query("SELECT SUM(subtotal) as suma FROM items WHERE items.sale_id = " . $datos['Item']['sale_id'] . ";");

                $venta['Sale']['total'] = $aux[0][0]['suma'];
                //Otra Manera de guardar campos!
                $this->Sale->id = $venta['Sale']['id'];
                if ($this->Sale->saveField('total', $venta['Sale']['total'])) {

                        //Actualizo el stock del articulo sumandole la cantidad del item
                        $articulo = $this->Article->find('first', array('conditions' => array('Article.id' => $datos['Item']['article_id'])));
//                        pr($articulo);
                        $articulo['Article']['amount_available'] = $articulo['Article']['amount_available'] + $datos['Item']['sale_amount'];
                        $this->Article->id = $articulo['Article']['id'];
                        $this->Article->saveField('total', $venta['Sale']['total']);
//                        pr($articulo);die;
                        if($this->Article->save($articulo['Article'])){
                            $bandera = true;
                        } else{
                            $bandera = false;
                        }                        
                    //Fin actualizacion articulo
                } else {
                    $bandera = false;
                }
            } else {
                $bandera = false;
            }
//		$this->Session->setFlash(__('Item no eliminado', true));
//		$this->redirect(array('action' => 'index'));
            if ($bandera) {
                $this->Item->query('COMMIT;');
                $this->Item->query('SET AUTOCOMMIT = 1;');
//                    $this->Session->setFlash(__('El item se ha eliminado', true));
                $this->redirect(array('controller' => 'sales', 'action' => 'view', $datos['Item']['sale_id']));
            } else {//si hubo algun error hago un ROLLBACK deshaciendo todas estas consultas
                $this->Item->query('ROLLBACK;');
                $this->Item->query('SET AUTOCOMMIT = 1;');
                $this->Session->setFlash(__('El item no pudo ser eliminado. Por favor, inténtalo de nuevo.', true));
            }
        }
    }

}
